// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/files/file_path_linux.h"

#include <string.h>
#include <algorithm>

#include "base/basictypes.h"
#include "base/logging.h"
#include "base/pickle.h"

// These includes are just for the *Hack functions, and should be removed
// when those functions are removed.
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"

namespace base {

#define LINUX_FILE_PATH_LITERAL(x) x
#define LINUX_PRFilePath "s"
#define LINUX_PRFilePathLiteral "%s"

typedef FilePathLinux::StringType StringType;

namespace {

const char* kCommonDoubleExtensionSuffixes[] = { "gz", "z", "bz2" };
const char* kCommonDoubleExtensions[] = { "user.js" };

const FilePathLinux::CharType kStringTerminator = LINUX_FILE_PATH_LITERAL('\0');

bool IsPathAbsolute(const StringType& path) {
  // Look for a separator in the first position.
  return path.length() > 0 && FilePathLinux::IsSeparator(path[0]);
}

bool AreAllSeparators(const StringType& input) {
  for (StringType::const_iterator it = input.begin();
      it != input.end(); ++it) {
    if (!FilePathLinux::IsSeparator(*it))
      return false;
  }

  return true;
}

// Find the position of the '.' that separates the extension from the rest
// of the file name. The position is relative to BaseName(), not value().
// This allows a second extension component of up to 4 characters when the
// rightmost extension component is a common double extension (gz, bz2, Z).
// For example, foo.tar.gz or foo.tar.Z would have extension components of
// '.tar.gz' and '.tar.Z' respectively. Returns npos if it can't find an
// extension.
StringType::size_type ExtensionSeparatorPosition(const StringType& path) {
  // Special case "." and ".."
  if (path == FilePathLinux::kCurrentDirectory || path == FilePathLinux::kParentDirectory)
    return StringType::npos;

  const StringType::size_type last_dot =
      path.rfind(FilePathLinux::kExtensionSeparator);

  // No extension, or the extension is the whole filename.
  if (last_dot == StringType::npos || last_dot == 0U)
    return last_dot;

  const StringType::size_type penultimate_dot =
      path.rfind(FilePathLinux::kExtensionSeparator, last_dot - 1);
  const StringType::size_type last_separator =
      path.find_last_of(FilePathLinux::kSeparators, last_dot - 1,
                        FilePathLinux::kSeparatorsLength - 1);

  if (penultimate_dot == StringType::npos ||
      (last_separator != StringType::npos &&
       penultimate_dot < last_separator)) {
    return last_dot;
  }

  for (size_t i = 0; i < arraysize(kCommonDoubleExtensions); ++i) {
    StringType extension(path, penultimate_dot + 1);
    if (LowerCaseEqualsASCII(extension, kCommonDoubleExtensions[i]))
      return penultimate_dot;
  }

  StringType extension(path, last_dot + 1);
  for (size_t i = 0; i < arraysize(kCommonDoubleExtensionSuffixes); ++i) {
    if (LowerCaseEqualsASCII(extension, kCommonDoubleExtensionSuffixes[i])) {
      if ((last_dot - penultimate_dot) <= 5U &&
          (last_dot - penultimate_dot) > 1U) {
        return penultimate_dot;
      }
    }
  }

  return last_dot;
}

// Returns true if path is "", ".", or "..".
bool IsEmptyOrSpecialCase(const StringType& path) {
  // Special cases "", ".", and ".."
  if (path.empty() || path == FilePathLinux::kCurrentDirectory ||
      path == FilePathLinux::kParentDirectory) {
    return true;
  }

  return false;
}

}  // namespace

FilePathLinux::FilePathLinux() {
}

FilePathLinux::FilePathLinux(const FilePathLinux& that) : path_(that.path_) {
}

FilePathLinux::FilePathLinux(const StringType& path) : path_(path) {
  StringType::size_type nul_pos = path_.find(kStringTerminator);
  if (nul_pos != StringType::npos)
    path_.erase(nul_pos, StringType::npos);
}

FilePathLinux::~FilePathLinux() {
}

FilePathLinux& FilePathLinux::operator=(const FilePathLinux& that) {
  path_ = that.path_;
  return *this;
}

bool FilePathLinux::operator==(const FilePathLinux& that) const {
  return path_ == that.path_;
}

bool FilePathLinux::operator!=(const FilePathLinux& that) const {
  return path_ != that.path_;
}

// static
bool FilePathLinux::IsSeparator(CharType character) {
  for (size_t i = 0; i < kSeparatorsLength - 1; ++i) {
    if (character == kSeparators[i]) {
      return true;
    }
  }

  return false;
}

void FilePathLinux::GetComponents(std::vector<StringType>* components) const {
  DCHECK(components);
  if (!components)
    return;
  components->clear();
  if (value().empty())
    return;

  std::vector<StringType> ret_val;
  FilePathLinux current = *this;
  FilePathLinux base;

  // Capture path components.
  while (current != current.DirName()) {
    base = current.BaseName();
    if (!AreAllSeparators(base.value()))
      ret_val.push_back(base.value());
    current = current.DirName();
  }

  // Capture root, if any.
  base = current.BaseName();
  if (!base.value().empty() && base.value() != kCurrentDirectory)
    ret_val.push_back(current.BaseName().value());

  *components = std::vector<StringType>(ret_val.rbegin(), ret_val.rend());
}

bool FilePathLinux::IsParent(const FilePathLinux& child) const {
  return AppendRelativePath(child, NULL);
}

bool FilePathLinux::AppendRelativePath(const FilePathLinux& child,
                                  FilePathLinux* path) const {
  std::vector<StringType> parent_components;
  std::vector<StringType> child_components;
  GetComponents(&parent_components);
  child.GetComponents(&child_components);

  if (parent_components.empty() ||
      parent_components.size() >= child_components.size())
    return false;

  std::vector<StringType>::const_iterator parent_comp =
      parent_components.begin();
  std::vector<StringType>::const_iterator child_comp =
      child_components.begin();

  while (parent_comp != parent_components.end()) {
    if (*parent_comp != *child_comp)
      return false;
    ++parent_comp;
    ++child_comp;
  }

  if (path != NULL) {
    for (; child_comp != child_components.end(); ++child_comp) {
      *path = path->Append(*child_comp);
    }
  }
  return true;
}

// libgen's dirname and basename aren't guaranteed to be thread-safe and aren't
// guaranteed to not modify their input strings, and in fact are implemented
// differently in this regard on different platforms.  Don't use them, but
// adhere to their behavior.
FilePathLinux FilePathLinux::DirName() const {
  FilePathLinux new_path(path_);
  new_path.StripTrailingSeparatorsInternal();

  // The drive letter, if any, always needs to remain in the output.  If there
  // is no drive letter, as will always be the case on platforms which do not
  // support drive letters, letter will be npos, or -1, so the comparisons and
  // resizes below using letter will still be valid.
  StringType::size_type letter = StringType::npos;

  StringType::size_type last_separator =
      new_path.path_.find_last_of(kSeparators, StringType::npos,
                                  kSeparatorsLength - 1);
  if (last_separator == StringType::npos) {
    // path_ is in the current directory.
    new_path.path_.resize(letter + 1);
  } else if (last_separator == letter + 1) {
    // path_ is in the root directory.
    new_path.path_.resize(letter + 2);
  } else if (last_separator == letter + 2 &&
             IsSeparator(new_path.path_[letter + 1])) {
    // path_ is in "//" (possibly with a drive letter); leave the double
    // separator intact indicating alternate root.
    new_path.path_.resize(letter + 3);
  } else if (last_separator != 0) {
    // path_ is somewhere else, trim the basename.
    new_path.path_.resize(last_separator);
  }

  new_path.StripTrailingSeparatorsInternal();
  if (!new_path.path_.length())
    new_path.path_ = kCurrentDirectory;

  return new_path;
}

FilePathLinux FilePathLinux::BaseName() const {
  FilePathLinux new_path(path_);
  new_path.StripTrailingSeparatorsInternal();

  // Keep everything after the final separator, but if the pathname is only
  // one character and it's a separator, leave it alone.
  StringType::size_type last_separator =
      new_path.path_.find_last_of(kSeparators, StringType::npos,
                                  kSeparatorsLength - 1);
  if (last_separator != StringType::npos &&
      last_separator < new_path.path_.length() - 1) {
    new_path.path_.erase(0, last_separator + 1);
  }

  return new_path;
}

StringType FilePathLinux::Extension() const {
  FilePathLinux base(BaseName());
  const StringType::size_type dot = ExtensionSeparatorPosition(base.path_);
  if (dot == StringType::npos)
    return StringType();

  return base.path_.substr(dot, StringType::npos);
}

FilePathLinux FilePathLinux::RemoveExtension() const {
  if (Extension().empty())
    return *this;

  const StringType::size_type dot = ExtensionSeparatorPosition(path_);
  if (dot == StringType::npos)
    return *this;

  return FilePathLinux(path_.substr(0, dot));
}

FilePathLinux FilePathLinux::InsertBeforeExtension(const StringType& suffix) const {
  if (suffix.empty())
    return FilePathLinux(path_);

  if (IsEmptyOrSpecialCase(BaseName().value()))
    return FilePathLinux();

  StringType ext = Extension();
  StringType ret = RemoveExtension().value();
  ret.append(suffix);
  ret.append(ext);
  return FilePathLinux(ret);
}

FilePathLinux FilePathLinux::InsertBeforeExtensionASCII(const StringPiece& suffix)
    const {
  DCHECK(IsStringASCII(suffix));
  return InsertBeforeExtension(suffix.as_string());
}

FilePathLinux FilePathLinux::AddExtension(const StringType& extension) const {
  if (IsEmptyOrSpecialCase(BaseName().value()))
    return FilePathLinux();

  // If the new extension is "" or ".", then just return the current FilePathLinux.
  if (extension.empty() || extension == StringType(1, kExtensionSeparator))
    return *this;

  StringType str = path_;
  if (extension[0] != kExtensionSeparator &&
      *(str.end() - 1) != kExtensionSeparator) {
    str.append(1, kExtensionSeparator);
  }
  str.append(extension);
  return FilePathLinux(str);
}

FilePathLinux FilePathLinux::ReplaceExtension(const StringType& extension) const {
  if (IsEmptyOrSpecialCase(BaseName().value()))
    return FilePathLinux();

  FilePathLinux no_ext = RemoveExtension();
  // If the new extension is "" or ".", then just remove the current extension.
  if (extension.empty() || extension == StringType(1, kExtensionSeparator))
    return no_ext;

  StringType str = no_ext.value();
  if (extension[0] != kExtensionSeparator)
    str.append(1, kExtensionSeparator);
  str.append(extension);
  return FilePathLinux(str);
}

bool FilePathLinux::MatchesExtension(const StringType& extension) const {
  DCHECK(extension.empty() || extension[0] == kExtensionSeparator);

  StringType current_extension = Extension();

  if (current_extension.length() != extension.length())
    return false;

  return FilePathLinux::CompareEqualIgnoreCase(extension, current_extension);
}

FilePathLinux FilePathLinux::Append(const StringType& component) const {
  const StringType* appended = &component;
  StringType without_nuls;

  StringType::size_type nul_pos = component.find(kStringTerminator);
  if (nul_pos != StringType::npos) {
    without_nuls = component.substr(0, nul_pos);
    appended = &without_nuls;
  }

  DCHECK(!IsPathAbsolute(*appended));

  if (path_.compare(kCurrentDirectory) == 0) {
    // Append normally doesn't do any normalization, but as a special case,
    // when appending to kCurrentDirectory, just return a new path for the
    // component argument.  Appending component to kCurrentDirectory would
    // serve no purpose other than needlessly lengthening the path, and
    // it's likely in practice to wind up with FilePathLinux objects containing
    // only kCurrentDirectory when calling DirName on a single relative path
    // component.
    return FilePathLinux(*appended);
  }

  FilePathLinux new_path(path_);
  new_path.StripTrailingSeparatorsInternal();

  // Don't append a separator if the path is empty (indicating the current
  // directory) or if the path component is empty (indicating nothing to
  // append).
  if (appended->length() > 0 && new_path.path_.length() > 0) {
    // Don't append a separator if the path still ends with a trailing
    // separator after stripping (indicating the root directory).
    if (!IsSeparator(new_path.path_[new_path.path_.length() - 1])) {
      // Don't append a separator if the path is just a drive letter.
        if (StringType::npos + 1 != new_path.path_.length()) {
        new_path.path_.append(1, kSeparators[0]);
      }
    }
  }

  new_path.path_.append(*appended);
  return new_path;
}

FilePathLinux FilePathLinux::Append(const FilePathLinux& component) const {
  return Append(component.value());
}

FilePathLinux FilePathLinux::AppendASCII(const StringPiece& component) const {
  DCHECK(IsStringASCII(component));
  return Append(component.as_string());
}

bool FilePathLinux::IsAbsolute() const {
  return IsPathAbsolute(path_);
}

bool FilePathLinux::EndsWithSeparator() const {
  if (empty())
    return false;
  return IsSeparator(path_[path_.size() - 1]);
}

FilePathLinux FilePathLinux::AsEndingWithSeparator() const {
  if (EndsWithSeparator() || path_.empty())
    return *this;

  StringType path_str;
  path_str.reserve(path_.length() + 1);  // Only allocate string once.

  path_str = path_;
  path_str.append(&kSeparators[0], 1);
  return FilePathLinux(path_str);
}

FilePathLinux FilePathLinux::StripTrailingSeparators() const {
  FilePathLinux new_path(path_);
  new_path.StripTrailingSeparatorsInternal();

  return new_path;
}

bool FilePathLinux::ReferencesParent() const {
  std::vector<StringType> components;
  GetComponents(&components);

  std::vector<StringType>::const_iterator it = components.begin();
  for (; it != components.end(); ++it) {
    const StringType& component = *it;
    // Windows has odd, undocumented behavior with path components containing
    // only whitespace and . characters. So, if all we see is . and
    // whitespace, then we treat any .. sequence as referencing parent.
    // For simplicity we enforce this on all platforms.
    if (component.find_first_not_of(LINUX_FILE_PATH_LITERAL(". \n\r\t")) ==
            std::string::npos &&
        component.find(kParentDirectory) != std::string::npos) {
      return true;
    }
  }
  return false;
}

// See file_path.h for a discussion of the encoding of paths on POSIX
// platforms.  These encoding conversion functions are not quite correct.

string16 FilePathLinux::LossyDisplayName() const {
  return WideToUTF16(SysNativeMBToWide(path_));
}

std::string FilePathLinux::MaybeAsASCII() const {
  if (IsStringASCII(path_))
    return path_;
  return std::string();
}

std::string FilePathLinux::AsUTF8Unsafe() const {
#if defined(OS_MACOSX) || defined(OS_CHROMEOS)
  return value();
#else
  return WideToUTF8(SysNativeMBToWide(value()));
#endif
}

string16 FilePathLinux::AsUTF16Unsafe() const {
#if defined(OS_MACOSX) || defined(OS_CHROMEOS)
  return UTF8ToUTF16(value());
#else
  return WideToUTF16(SysNativeMBToWide(value()));
#endif
}

// The *Hack functions are temporary while we fix the remainder of the code.
// Remember to remove the #includes at the top when you remove these.

// static
FilePathLinux FilePathLinux::FromWStringHack(const std::wstring& wstring) {
  return FilePathLinux(SysWideToNativeMB(wstring));
}

// static
FilePathLinux FilePathLinux::FromUTF8Unsafe(const std::string& utf8) {
#if defined(OS_MACOSX) || defined(OS_CHROMEOS)
  return FilePathLinux(utf8);
#else
  return FilePathLinux(SysWideToNativeMB(UTF8ToWide(utf8)));
#endif
}

// static
FilePathLinux FilePathLinux::FromUTF16Unsafe(const string16& utf16) {
#if defined(OS_MACOSX) || defined(OS_CHROMEOS)
  return FilePathLinux(UTF16ToUTF8(utf16));
#else
  return FilePathLinux(SysWideToNativeMB(UTF16ToWide(utf16)));
#endif
}


void FilePathLinux::WriteToPickle(Pickle* pickle) const {
  pickle->WriteString(path_);
}

bool FilePathLinux::ReadFromPickle(PickleIterator* iter) {
  if (!iter->ReadString(&path_))
    return false;

  if (path_.find(kStringTerminator) != StringType::npos)
    return false;

  return true;
}


void FilePathLinux::StripTrailingSeparatorsInternal() {
  // If there is no drive letter, start will be 1, which will prevent stripping
  // the leading separator if there is only one separator.  If there is a drive
  // letter, start will be set appropriately to prevent stripping the first
  // separator following the drive letter, if a separator immediately follows
  // the drive letter.
  StringType::size_type start = StringType::npos + 2;

  StringType::size_type last_stripped = StringType::npos;
  for (StringType::size_type pos = path_.length();
       pos > start && IsSeparator(path_[pos - 1]);
       --pos) {
    // If the string only has two separators and they're at the beginning,
    // don't strip them, unless the string began with more than two separators.
    if (pos != start + 1 || last_stripped == start + 2 ||
        !IsSeparator(path_[start - 1])) {
      path_.resize(pos - 1);
      last_stripped = pos;
    }
  }
}

FilePathLinux FilePathLinux::NormalizePathSeparators() const {
  return *this;
}

}  // namespace base

void PrintTo(const base::FilePathLinux& path, std::ostream* out) {
  *out << path.value();
}
